<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card company_box">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <!-- 新增按钮 -->
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="editRoleDialog=true">新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="roles" style="width: 100%" border>
              <el-table-column type="index" label="序号" width="150" />
              <el-table-column prop="name" label="角色名" width="150" sortable />
              <el-table-column prop="description" label="描述" sortable />
              <el-table-column label="操作" width="250" align="center">
                <template v-slot="{row}">
                  <el-button type="text" size="mini" @click="onSetPermission(row)">分配权限</el-button>
                  <el-button type="text" size="mini" @click="onEditRole(row)">修改</el-button>
                  <el-button type="text" size="mini" @click="onDelRoles(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              :current-page="page.page"
              :page-size="page.pagesize"
              layout="total, prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="info">
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称" prop="name">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址" prop="companyAddress">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司电话" prop="companyPhone">
                <el-input v-model="formData.companyPhone" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱" prop="mailbox">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 修改/新增 角色的弹出框 -->
    <el-dialog
      :title="titleText"
      :visible.sync="editRoleDialog"
      width="50%"
      @close="onDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 的弹出框 -->
    <el-dialog
      :title="setPermissionTitle"
      :visible.sync="setPermissionDialog"
      width="50%"
      @close="onClose"
    >
      <el-tree
        v-if="setPermissionDialog"
        ref="setPermissionTree"
        :data="permissionList"
        :props="defaultProps"
        icon-class=" "
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultKeys"
        check-strictly
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setPermissionDialog = false">取 消</el-button>
        <el-button type="primary" @click="onSetPermissionSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, delRole, getRoleById, updateRole, addRole, getCompanyInfo } from '@/api/company.js'
import { mapGetters } from 'vuex'
import { getPermissionList, setPermissionToRole } from '@/api/permission'
import { listToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role', // 控制默认选中
      roles: [],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      // 控制 修改/新增 角色的弹出框显示隐藏
      editRoleDialog: false,
      // 编辑/新增 表单数据
      form: {
        name: '',
        description: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ]
      },
      // 公司 数据
      formData: {
        name: '', // 公司名称
        companyAddress: '', // 公司地址
        companyPhone: '', // 公司电话
        mailbox: '', // 邮箱
        remarks: '' // 备注
      },
      // 控制 分配权限 的弹出框显示隐藏
      setPermissionDialog: false,
      // 分配权限 动态标题
      setPermissionTitle: '',
      // 分配权限 数据
      permissionList: [],
      // 分配权限 配置选项
      defaultProps: {
        label: 'name'
      },
      // 树形 默认选中
      defaultKeys: [],
      roleId: ''
    }
  },
  computed: {
    // 修改/新增 动态标题
    titleText() {
      return (this.form.id ? '编辑' : '新增') + '角色'
    },
    ...mapGetters(['companyId'])
  },
  created() {
    this.loadRoleList()
    this.loadCompanyInfo()
  },

  methods: {
    // 加载角色列表
    async loadRoleList() {
      const res = await getRoleList(this.page)
      this.roles = res.rows
      this.total = res.total
    },
    // 当前页发生变化
    handleCurrentChange(val) {
      this.page.page = val
      this.loadRoleList()
    },
    // 点击删除
    onDelRoles(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRole(id)
        this.$message.success('删除成功')
        this.loadRoleList()
      }).catch(() => {})
    },
    // 点击编辑
    async onEditRole(row) {
      const res = await getRoleById(row.id)
      this.form = res
      this.editRoleDialog = true
    },
    // 点击了 修改/新增 弹出框的确定按钮
    async onSave() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 编辑
          await updateRole(this.form)
          this.$message.success('更新成功')
        } else {
          // 新增
          await addRole(this.form)
          this.$message.success('新增成功')
        }

        this.editRoleDialog = false
        this.loadRoleList()
      } catch (err) {
        console.log(err)
      }
    },
    // 监听 修改/新增 弹出框关闭
    onDialogClose() {
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 公司信息
    async loadCompanyInfo() {
      const res = await getCompanyInfo(this.companyId)
      this.formData = res
    },
    // 点击分配权限
    async onSetPermission(row) {
      this.roleId = row.id
      this.setPermissionTitle = '为【' + row.name + '】分配权限'
      this.setPermissionDialog = true
      // 获取所有的权限
      const res = await getPermissionList()
      this.permissionList = listToTree('0', res)
      // 获取当前角色所拥有的权限
      this.defaultKeys = (await getRoleById(row.id)).permIds
    },
    // 点击 分配权限 弹出框的确定按钮
    async onSetPermissionSave() {
      const permissionIds = this.$refs.setPermissionTree.getCheckedKeys()
      if (!permissionIds.length) return this.$message.error('请选择必要的权限')
      await setPermissionToRole({
        id: this.roleId,
        permIds: permissionIds
      })
      this.$message.success('分配成功')
      this.setPermissionDialog = false
    },
    // 监听 分配权限 弹出框关闭
    onClose() {
      this.defaultKeys = []
    }
  }
}
</script>

<style scoped lang="scss">
.company_box{
  ::v-deep.el-tabs__item{
    width: 150px;
    font-size: 18px;
    text-align: center;
    padding: 0 30px;
  }
  .el-pagination{
    display: flex;
    justify-content: flex-end;
  }
}
</style>
